<template>
	<view style="padding-bottom: 50upx;">
		<view class="tabtop">
			<scroll-view scroll-x="true" class="scroll-view_H">
				<view class="hd-box-item" @click="bindopen(index,item)" v-for="(item,index) in list" :key="index"
					:class="current==index?'act':''">
					{{item.serviceName}}
				</view>
			</scroll-view>
		</view>
		<view class="boxa" v-for="(item,index) in orderList" :key="index" @click="goOrder(item.indentId)">
			<view class="flex align-center justify-between padding-lr">
				<view class="flex align-center">
					<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/huoyunsf/image/data.png" style="width: 34rpx;height: 38rpx;"></image>
					<view class="margin-left-sm">{{item.indentType===1?'立即用车':'预约用车'}}</view>
				</view>
				<view v-if="item.indentType != 1">时间:{{setTimeSplice(item.hopeTime)}}</view>
			</view>
			<view class="margin-tb-sm" style="width: 100%;height:1rpx;background: #F2F2F2;"></view>
			
			<view v-for="(addr,aindex) in item.addressList" :key="addr.addressId">
				<view class="addbox bgs margin-lr margin-bottom" v-if="aindex == 0">
					<view class="add_cont">
						<view class="green"></view>
						<view class="add_tit">
							<view>{{addr.address}}</view>
						</view>
					</view>
				</view>
				
				<view class="addbox bgss margin-lr" v-else-if="aindex == item.addressList.length-1">
					<view class="add_cont">
						<view class="orgin"></view>
						<view class="add_tit">
							<view>{{addr.address}}</view>
						</view>
					</view>
				</view>
				
				<view class="addbox bg margin-lr margin-bottom" v-else>
					<view class="add_cont">
						<view class="gray"></view>
						<view class="add_tit">
							<view>{{addr.address}}</view>
						</view>
					</view>
				</view>
			</view>
			
			
			<!-- <view class="addbox bgs margin-lr margin-bottom">
				<view class="add_cont">
					<view class="green"></view>
					<view class="add_tit">
						<view>{{item.startAddress}}</view>
					</view>
				</view>
			</view>
			<view class="addbox bg margin-lr">
				<view class="add_cont">
					<view class="orgin"></view>
					<view class="add_tit">{{item.endAddress}}</view>
				</view>
			</view> -->
			
			<view class="margin-tb-sm" style="width: 100%;height:1rpx;background: #F2F2F2;"></view>
			<view class="flex align-center justify-between padding-lr ">
				<view class="flex align-center">
					<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/huoyunsf/image/add.png" style="width: 30rpx;height: 35rpx;"></image>
					<view class="margin-left-xs">距您<text style="color: #3699FF;">{{item.distance}}</text>
					</view>
				</view>
				<view class="flex align-center">预估
					<view style="color: #FF2020;font-size: 32rpx;">
						<text>¥</text><text class="text-bold" style="font-size: 42rpx;">{{item.riderMoney}}</text>
					</view>
				</view>
			</view>
			<view class="btn">抢单</view>
		</view>
		<empty v-if="orderList.length == 0" />
	</view>
</template>

<script>
	import empty from '@/components/empty'
	export default {
		components: {
			empty
		},
		onShareAppMessage(res) { //发送给朋友
			return {
				title: this.tuiguang,
				path: '/pages/index/index',
				imageUrl: this.tuiguangImg,
			}
		},
		onShareTimeline(res) { //分享到朋友圈
			return {
				title: this.tuiguang,
				path: '/pages/index/index',
				imageUrl: this.tuiguangImg,
			}
		},
		data() {
			return {
				current: 0,
				list: [],
				tuiguang: '', //分享标题
				tuiguangImg: '', //分享图片
				time: null, //订单定时器
				orderList: [],
				page: 1,
				limit: 10,
				pages: 1,
				latitude: '',
				longitude: '',
				token: '',
				arr: [], //通知数组
				checkCertificationMessage: '', //拒绝原因
				checkCertification: '', //认证状态
				showModal1: true,
			}
		},
		onHide() {
			//清除定时器
			clearInterval(this.time)
			this.time = null

		},
		onLoad() {
			this.getcarType();

		},
		onShow() {
			if (this.time) {
				clearInterval(this.time)
				this.time = null
			}
			let that = this;
			that.$Request.getT('/app/common/type/276').then(res => {
				if (res.code === 0) {
					uni.setStorageSync('tuiguang', res.data.value)
					this.tuiguang = res.data.value;
				}
			});
			that.$Request.getT('/app/common/type/277').then(res => {
				if (res.code === 0) {
					uni.setStorageSync('tuiguangImg', res.data.value)
					that.tuiguangImg = res.data.value;
				}
			});
			that.$Request.getT('/app/common/type/338').then(res => { //师傅新订单通知
				if (res.code == 0) {
					if (res.data && res.data.value) {
						that.arr.push(res.data.value)
					}
				}
			})
			that.$Request.getT('/app/common/type/268').then(res => { //订单状态通知
				if (res.code == 0) {
					if (res.data && res.data.value) {
						that.arr.push(res.data.value)
					}
				}
			})
			that.token = uni.getStorageSync('token')
			if (that.showModal1) {
				// #ifdef MP-WEIXIN
				that.openMsg()
				// #endif
			}

			if (that.token) {
				uni.showLoading({
					title: '加载中'
				})
				uni.getLocation({
					type: 'gcj02', //返回可以用于uni.openLocation的经纬度
					success: function(res) {
						that.latitude = res.latitude
						that.longitude = res.longitude
						let data = {
							lat: res.latitude,
							lng: res.longitude
						}
						that.$Request.getT('/app/Login/selectCity', data).then(res => {
							if (res.code === 0) {
								that.province = res.data.province
								that.city = res.data.city
								that.district = res.data.district
							}
						});
						that.getLocation()
						that.taskData()
						that.getNewOrder()
					}
				});
				that.time = setInterval(function() {
					uni.getLocation({
						type: 'gcj02', //返回可以用于uni.openLocation的经纬度
						success: function(res) {
							that.latitude = res.latitude
							that.longitude = res.longitude
							let data = {
								lat: res.latitude,
								lng: res.longitude
							}
							that.$Request.getT('/app/Login/selectCity', data).then(res => {
								if (res.code === 0) {
									that.province = res.data.province
									that.city = res.data.city
									that.district = res.data.district
								}
							});
							that.getLocation()
							that.taskData()
							that.getNewOrder()
						}
					});
				}, 5000)
				that.getUserInfo();

				// that.$Request.getT('/app/common/type/292').then(res => { //接单成功
				// 	if (res.code == 0) {
				// 		if (res.data && res.data.value) {
				// 			that.arr.push(res.data.value)
				// 		}
				// 	}
				// })



			} else {
				that.orderList = []
			}
		},
		methods: {
			getNewOrder() {
				this.$Request.getT('/app/message/getOrderMessage').then(res => {
					if (res.code == 0) {
						if (res.data > 0) {
							console.log('11111111')
							this.aplayAudio()
						}
						console.log(res.data, 'aplayAudio')
					}
				});
			},
			//接单池刷新
			aplayAudio() {
				// console.log('语音提示')
				const innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				// innerAudioContext.src ='https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/huoyunsf/mpc/order.mp3';
				innerAudioContext.src =
					'https://pw.xianmxkj.com/file/uploadPath/2022/01/19/0753211f78d718d44ee6372e33eae9ee.mp3';
				innerAudioContext.onPlay(() => {
					console.log('开始播放');
				});
				innerAudioContext.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
			},
			// 上传师傅位置
			getLocation() {
				let data = {
					lng: this.longitude,
					lat: this.latitude,
					userId: uni.getStorageSync('userId'),
					province: this.province,
					city: this.city,
					district: this.district,
				}
				this.$Request.getT('/timedtask/riderLocation', data).then(res => {
					if (res.code == 0) {
						console.log('上传师傅位置')
					}
				});
			},
			getcarType() { //货运车型
				// let data = {
				// 	type: 1,
				// }
				this.$Request.getT('/app/serviceType/getServiceList').then(res => {
					if (res.code == 0) {
						let datas = {
							serviceId: '',
							serviceName: "全部"
						}
						this.list = [];
						this.list.push(datas);
						res.data.records.forEach(d => {
							this.list.push(d)
						});
						// this.list = res.data.records
						// this.serviceId = res.data.records[0].serviceId
						// this.listWeight = res.data.records[0]
						// this.getcartype()
						// this.getCarModelList()
					}
				})
			},
			//截取时间到分钟
			setTimeSplice(time) {
				let temp = ''
				if (time) {
					temp = time.substring(0, 16)
				}
				return temp
			},
			//获取个人信息
			getUserInfo() {
				this.$Request.getT('/app/userinfo/findUserInfoById').then(res => {
					if (res.code == 0) {
						this.checkCertification = res.data.checkCertification
						this.checkCertificationMessage = res.data.checkCertificationMessage
					} else {
						this.$queue.logout();
						uni.showModal({
							showCancel: false,
							title: '登录失败',
							content: res.msg,
						});
					}
				})
			},
			//跳转到接单详情
			goOrder(indentId) {
				// uni.navigateTo({
				// 	url: '/pages/index/orderDet?indentId=' + indentId
				// })
				// return
				// #ifdef MP-WEIXIN
				if (uni.getStorageSync('sendMsg')) {
					uni.requestSubscribeMessage({
						tmplIds: this.arr,
						success(re) {
							// console.log(re,'**********')
							var datas = JSON.stringify(re);
							if (datas.indexOf("accept") != -1) {
								console.log(re)
							}
						},
						fail: (res) => {
							console.log(res)
						}
					})
				}
				// #endif
				console.log(this.checkCertification, '222222222')
				if (this.checkCertification == null || this.checkCertification == '') {
					uni.showModal({
						title: '提示',
						content: '实名认证后才可接单',
						confirmText: '去认证',
						complete(ret) {
							if (ret.confirm) {
								uni.navigateTo({
									url: '/my/renzheng/index'
								})
							}
						}
					})
				} else if (Number(this.checkCertification) == 0) {
					uni.showModal({
						title: '提示',
						content: '实名认证审核中',
						confirmText: '去查看',
						complete(ret) {
							if (ret.confirm) {
								uni.navigateTo({
									url: '/my/renzheng/index'
								})
							}
						}
					})
				} else if (Number(this.checkCertification) == 1) {
					uni.navigateTo({
						url: '/pages/index/orderDet?indentId=' + indentId
					})
				} else if (Number(this.checkCertification) == 2) {
					uni.showModal({
						title: '提示',
						content: '实名认证未通过：' + this.checkCertificationMessage,
						confirmText: '去认证',
						complete(ret) {
							if (ret.confirm) {
								uni.navigateTo({
									url: '/my/renzheng/index'
								})
							}
						}
					})
				}
			},
			bindopen(index, item) {
				this.current = index
				this.page = 1
				this.taskData()
			},
			// 获取新任务数据
			taskData() {
				let serviceId = '';
				if (this.list.length > 0) {
					serviceId = this.list[this.current].serviceId;
				}
				this.$Request.getT('/app/indent/findNewIndent', {
					page: this.page,
					limit: this.limit,
					od: this.latitude,
					ol: this.longitude,
					serviceId: serviceId,
				}).then(res => {
					uni.hideLoading()
					uni.stopPullDownRefresh();
					if (res.code == 0) {
						if (res.data) {
							this.pages = res.data.pages
							res.data.records.map(item => {
								if (item.distance > 1) {
									item.distance = item.distance + 'km'
								} else {
									item.distance = (parseFloat(item.distance) * 1000).toFixed(2) + "m"
								}
							})
							if (this.page == 1) {
								this.orderList = res.data.records
							} else {
								this.orderList = [...this.orderList, ...res.data.records]
							}
						}
					}
				});
			},
			// 开启订阅消息
			openMsg() {
				console.log('订阅消息')
				var that = this
				uni.getSetting({
					withSubscriptions: true, //是否获取用户订阅消息的订阅状态，默认false不返回
					success(ret) {
						console.log(ret.subscriptionsSetting, '------------------')
						// if (ret.subscriptionsSetting.itemSettings && Object.keys(ret.subscriptionsSetting.itemSettings).length == 2) {
						if (ret.subscriptionsSetting.itemSettings) {
							uni.setStorageSync('sendMsg', true)
							uni.openSetting({ // 打开设置页 
								success(rea) {
									console.log(rea.authSetting)
								}
							});
						} else { // 用户没有点击“总是保持以上，不再询问”则每次都会调起订阅消息
							console.log(99999)
							uni.setStorageSync('sendMsg', false)
							uni.showModal({
								title: '提示',
								content: '为了更好的体验,请绑定消息推送',
								confirmText: '确定',
								cancelText: '取消',
								success: function(res) {
									if (res.confirm) {
										console.log(that.arr)
										wx.requestSubscribeMessage({
											tmplIds: that.arr,
											success(re) {
												console.log(JSON.stringify(re),
													'++++++++++++++')
												var datas = JSON.stringify(re);
												if (datas.indexOf("accept") != -1) {
													console.log(re)
													// uni.setStorageSync('sendMsg', true)
												}
											},
											fail: (res) => {
												console.log(res)
											}
										})
										// uni.setStorageSync('sendMsg', true)
										console.log('确认')
										that.showModal1 = false
									} else if (res.cancel) {
										console.log('取消')
										// uni.setStorageSync('sendMsg', false)
										that.showModal1 = true
									}
								}
							})
						}
					}
				})
			},
		},
		// 上拉加载
		onReachBottom: function() {
			if (uni.getStorageSync('token')) {
				if (this.page < this.pages) {
					this.page += 1
					this.taskData();
				} else {
					uni.showToast({
						title: '已经最后一页啦',
						icon: 'none'
					})
				}
			}

		},
		onPullDownRefresh: function() {
			if (uni.getStorageSync('token')) {
				this.page = 1;
				this.taskData();
			} else {
				uni.stopPullDownRefresh()
			}


		},
	}
</script>

<style lang="less">
	page {
		background: #F5F5F5;
	}

	.tabtop {
		background: #FFFFFF;
		padding: 10rpx 30rpx;
	}

	.scroll-view_H {
		width: 100%;
		white-space: nowrap;

	}

	.hd-box-item {
		display: inline-block;
		padding: 10rpx 25rpx 10rpx 25rpx;
		font-size: 28rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #333333;
		margin-right: 10rpx;
	}

	.hd-box-items {
		display: inline-block;
		padding: 10rpx 25rpx 10rpx 25rpx;
		font-size: 28rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #FFFFFF;

		margin-right: 25rpx;
	}

	.act {
		background: #F2FFF9;
		border: 1rpx solid #02B595;
		border-radius: 30rpx;
		font-size: 28rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #02B595;
	}

	.boxa {
		background: #FFFFFF;
		border-radius: 24rpx;
		margin: 30rpx;
		padding: 30rpx 0;
	}


	.addbox {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 30rpx;
		height: 110rpx;
		border-radius: 16rpx;

	}

	.add_cont {
		display: flex;
		align-items: center;
	}

	.add_tit {
		font-size: 30rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #333333;
	}

	.bg {
		background: #F5F5F5;
	}

	.bgs {
		background: #F5F8FF;

	}
	
	.bgss {
		background: #faf3e3;
	
	}

	.green {
		width: 16rpx;
		height: 16rpx;
		background: #1FC657;
		border-radius: 50%;
		margin-right: 20rpx;
	}
	.gray {
		width: 16rpx;
		height: 16rpx;
		background: #cccccc;
		border-radius: 50%;
		margin-right: 20rpx;
	}
	.orgin {
		width: 16rpx;
		height: 16rpx;
		background: #FBAC04;
		border-radius: 50%;
		margin-right: 20rpx;
	}

	.btn {
		height: 78rpx;
		background: #02B595;
		border-radius: 4rpx;
		font-size: 28rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #FFFFFF;
		margin: 30rpx 30rpx 0;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>